<?php

declare (strict_types = 1);

namespace app\middleware;

use think\facade\Session;
use think\Request;
use think\Response;
use Closure;

class AuthMiddleware
{
     /**
     * 处理请求 - 验证用户登录状态
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle(Request $request, Closure $next, ?string $redirectToRoute = null)
    {
        // 根据 user_id 检查用户是否已登录
        if (Session::has('user_id')) {
            // 如果已登录，重定向到指定页面
            $redirectUrl = $redirectToRoute ? (string) url($redirectToRoute) : '/';
            return redirect($redirectUrl);
        }

        // 如果未登录，继续执行后续操作
        return $next($request);
    }
}